package com.spm.librarianmanagersystem.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spm.librarianmanagersystem.service.ReservationService;
import com.spm.librarianmanagersystem.utils.JsonResult;
import com.spm.librarianmanagersystem.utils.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class ReservationController {
    @Autowired
    ReservationService service;

    @GetMapping("/api/reservation")
    public JsonResult<JSONArray> getReservations() {
        String currentUserId = UserContextHolder.getCurrentUserId();
        return new JsonResult<>(service.getReservations(currentUserId));
    }

    @GetMapping("/api/reservation/detail")
    public JsonResult<JSONObject> getOneReservation(@RequestParam("reservation_id") Integer reservationId) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        return new JsonResult<>(service.getOneReservation(currentUserId, reservationId));
    }

    @PostMapping("/api/user/reservation/add")
    public JsonResult<String> reserve(@RequestBody JSONObject jsonObject) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        try {
            String msg = service.reserve(currentUserId, jsonObject.getString("ISBN"));
            return new JsonResult<>(0, msg);
        } catch (Exception e) {
            return new JsonResult<>(1, e.getMessage());
        }
    }

    @PostMapping("/api/user/reservation/cancel")
    public JsonResult<String> cancel(@RequestBody JSONObject jsonObject) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        try {
            String msg = service.cancel(currentUserId, jsonObject.getInteger("reservation_id"));
            return new JsonResult<>(0, msg);
        } catch (Exception e) {
            return new JsonResult<>(1, e.getMessage());
        }
    }

    @GetMapping("/api/admin/reservations/detail")
    public JsonResult<JSONArray> getReservationsAdminDetail() {
        return new JsonResult<>(service.getReservationsAdminDetail());
    }
}
